package org.llc.flink.study.example

import scala.collection.mutable


object Map1 {
  def main(args: Array[String]): Unit = {
    val sentence = "AAAAAAAAAABBBBBBBBCCCCCDDDDDDD"
    val map1 = Map[Char, Int]()

    // 先创建一个可变map,作为左折叠的第一个参数
    val res1 = sentence.foldLeft(map1)(charCount1)
    //res1 = Map(A -> 10, B -> 8, C -> 5, D -> 7)
    println("res1 = " + res1)

    // 使用可变的map效率更高
    val map2 = mutable.Map[Char, Int]()
    val res2 = sentence.foldLeft(map2)(charCount2)
    // res2 = Map(D -> 7, A -> 10, C -> 5, B -> 8)
    println("res2 = " + res2)
  }

  /**
    * @param map 不可变的map
    * @param char
    * @return
    */
  def charCount1(map: Map[Char, Int], char: Char): Map[Char, Int] = {
    map + (char -> (map.getOrElse(char, 0) + 1))
  }

  /**
    * @param map 可变的map
    * @param char
    * @return
    */
  def charCount2(map: mutable.Map[Char, Int], char: Char): mutable.Map[Char, Int] = {
    map += (char -> (map.getOrElse(char, 0) + 1))
  }
}
